<?php

class LeftMenuWidget extends CWidget
{

    public $items;
    public $selectIds;

    private $_html = '';

    public function init()
    {
        $oCategories = new Categories();

        $oCategoryProperty = new CategoryProperty();
	    $this->items = $oCategoryProperty->getByType($this->selectIds, 2);

        $ids = $oCategories->getAllChild($this->selectIds);

	    $items = $oCategories->getUsedCategories($ids);
//        $items = $oCategories->onlyPublic()->id($ids)->findAll();

	    foreach($this->items as $i => $arr)
		    $this->items[$i]['childNodes'] = $items;
    }

    public function run()
    {
        $this->_tree($this->items);
    }

    protected function _tree($items, $level = 1, $propertyId = null, $valueId = null)
    {
	    if(!$items)
		    return $this->_html = '';

        $this->_html .= '<ul class="'. ($level == 1 ? ' categories' : '') .'">';


	    $request = '';
	    if($propertyId > 0 && $valueId > 0)
	        $request = '?v='. $propertyId .':'. $valueId;

        foreach($items as $i => $oRow)
        {
	        $this->_html .= '<li'. (isset($oRow->id) && isset($this->selectIds[$oRow->id]) ? ' class="selected"' : '') .'>';

	        if(!empty($oRow->type))
                $this->_html .= '<a href="'. Yii::app()->controller->createUrl('/'. ($oRow->type ? $oRow->type : 'category') .'/default/index', array('category_id' => $oRow->alias)) . $request .'">'. $oRow->title .'</a>';
	        else
                $this->_html .= '<div>'. $oRow['value'] .'</div>';

            if(!empty($oRow['childNodes']))
            {
                $this->_tree(
	                $oRow['childNodes'],
	                $level+1,
	                (!empty($oRow['property_id']) ? $oRow['property_id'] : null),
	                (!empty($oRow['id']) ? $oRow['id'] : null)
                );
            }

            $this->_html .= '</li>';
        }

        $this->_html .= '</ul>';

        return $this->_html;
    }

    public function __toString()
    {
//        $this->_html = '<div class="title">Категории</div>' . $this->_html;

//	    var_dump($this->_html);

	    if($this->_html)
		    $this->_html = '<div id="left-menu">'. $this->_html .'</div>';

        return $this->_html;
    }


}